package com.libui.thirdpartsdk.wechat

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.RECEIVER_EXPORTED
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import com.libui.BaseApplication
import com.libui.thirdpartsdk.SDKInterface
import com.libui.thirdpartsdk.login.Login
import com.libui.thirdpartsdk.share.ShareInterface
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.rxjava3.subjects.PublishSubject


class WechatSDK : SDKInterface, IWXAPIEventHandler {
    companion object {
        private const val TAG = "WechatSDK"

        val builder = object : SDKInterface.Builder {
            override val type: String = "wechat"

            override val sdkVersion: String? = null

            override val loginBuilder: Login.Builder = WechatLogin.builder

            override val shareBuilders: List<ShareInterface.Builder> = listOf(
                WechatShare.builder,
                WechatGroupShare.builder,
            )

            override fun build(): SDKInterface {
                return WechatSDK()
            }
        }

        var APP_ID: String? = null
    }

    override val type: String
        get() = builder.type

    override val loginBuilder: Login.Builder?
        get() = builder.loginBuilder

    override val shareBuilders: List<ShareInterface.Builder>?
        get() = builder.shareBuilders

    override val sdkVersion: String?
        get() = builder.sdkVersion

    override val isAppInstalled: Boolean
        get() = wxApi.isWXAppInstalled

    // IWXAPI 是第三方 app 和微信通信的 openApi 接口
    lateinit var wxApi: IWXAPI

    val authRespObservable = PublishSubject.create<SendAuth.Resp>()

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    override fun install(): Boolean {
        return BaseApplication.instance?.let {
            APP_ID?.let { appId ->
                wxApi = WXAPIFactory.createWXAPI(it, appId, true)
                wxApi.registerApp(appId)

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    it.registerReceiver(
                        object : BroadcastReceiver() {
                            override fun onReceive(context: Context, intent: Intent) {
                                wxApi.registerApp(appId)
                            }
                        },
                        IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP),
                        RECEIVER_EXPORTED
                    )
                } else {
                    it.registerReceiver(
                        object : BroadcastReceiver() {
                            override fun onReceive(context: Context, intent: Intent) {
                                wxApi.registerApp(appId)
                            }
                        },
                        IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP),
                    )
                }

                true
            } ?: false
        } ?: false
    }

    override fun uninstall() {
    }

    override fun handleIntent(intent: Intent): Boolean {
        return wxApi.handleIntent(intent, this)
    }

    override fun onReq(req: BaseReq) {
        Log.i(TAG, "onReq ${req.type}")
    }

    override fun onResp(resp: BaseResp) {
        Log.i(TAG, "onResp ${resp.type}")

        if (resp.type == ConstantsAPI.COMMAND_SENDAUTH) {
            authRespObservable.onNext(resp as SendAuth.Resp)
        }
    }
}